package com.itheima.web;

import com.alibaba.fastjson.JSON;
import com.itheima.pojo.Brand;
import com.itheima.service.BrandService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.BufferedReader;
import java.io.IOException;

@WebServlet("/addServlet")
public class AddServlet extends HttpServlet {
    // 如果使用axios发送post请求,参数是json格式,服务器getParameter取不到数据
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        BrandService brandService = new BrandService();

        // 1.接收数据,request.getParameter 不能接收json的数据
        String brandName = request.getParameter("brandName");
        System.out.println("brandName = " + brandName);

        // 获取请求体数据
        BufferedReader reader = request.getReader();
        String json = reader.readLine();
        System.out.println("param = " + json);

        // 将JSON字符串转为Java对象
        Brand brand = JSON.parseObject(json, Brand.class);

        response.setContentType("text/json;charset=utf-8");
        // 没有输入品牌名称,响应失败
        if (brand.getBrandName().equals("")) {
            response.getWriter().write("failure");
            return;
        }

        // 2.调用service 添加
        brandService.add(brand);

        // 3.响应成功标识
        response.getWriter().write("success");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}